package pl.enigmatic.runtime;

import java.io.IOException;
import java.io.InputStream;

import pl.enigmatic.util.Arrays;


public class Executable {

	private final String path;

	public Executable(final String path) {
		this.path = path;
	}

	public boolean execute(final boolean wait, final String... args) {
		try {
			final Process process = Runtime.getRuntime().exec(Arrays.concatenate(new String[] { path }, args));
			final String name = toString();
			new InputStreamReader(name + " ErrorStream", process.getErrorStream()).start();
			new InputStreamReader(name + " InputStream", process.getInputStream()).start();
			if (wait) {
				try {
					process.waitFor();
				} catch (final InterruptedException e) {}
			}
		} catch (final IOException e) {
			return false;
		}
		return true;
	}

	public String getPath() {
		return path;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + " [" + (path != null ? "path=" + path : "") + "]";
	}
}


class InputStreamReader extends Thread {

	private final InputStream stream;

	public InputStreamReader(final String name, final InputStream stream) {
		super(name);
		setDaemon(true);
		this.stream = stream;
	}

	@Override
	public void run() {
		final byte[] buffer = new byte[255];
		int read = 0;
		do {
			try {
				read = stream.read(buffer);
			} catch (final IOException e) {}
		} while (read > -1);

	}
}
